package com.sdy.dcsb.web.config;

import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.constants.OtherConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

/**
 * 全局异常控制
 * @author Snaky
 * @date 2020/1/8 17:55
 */
@Slf4j
@RestController
public class GlobalErrorController extends AbstractErrorController {

    private static final String ERROR_PATH = "/error";

    private ErrorAttributes errorAttributes;


    public GlobalErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }


    /**
     * Web页面错误处理,，默认错误页面
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public ModelAndView errorPageHandler(HttpServletRequest request, HttpServletResponse response) {

        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, getTraceParameter(request)));
        response.setStatus(status.value());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null?modelAndView:new ModelAndView("error", model);

    }

    /**
     * 除Web页面外的错误处理，比如Json/XML等
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public Response errorApiHandler(HttpServletRequest request, final WebRequest req) {

        Map<String, Object> attr = this.errorAttributes.getErrorAttributes(req, false);

        String msg = String.valueOf(attr.getOrDefault("message", "error"));
        log.info(OtherConstants.PREFIX_LOG + msg);
        return Response.error(msg,getStatus(request).value());
    }
}
